#encoding: utf-8 
require 'rubygems'
require 'nokogiri'
require 'open-uri'

namespace :db do
  namespace :hot do
    task :load => :environment do
      #Category.delete_all
      #Video.delete_all
      load_hot
    end

    task :reset => :environment do
      Category.delete_all
      Video.delete_all
    end

    def load_hot
      #system "mkdir -p #{Rails.root.to_s}/tmp/assets"
      puts "load Hot......\n"
      {
        'http://all.wasu.cn/index/cid/22' => '资讯',
        'http://all.wasu.cn/index/cid/26' => '娱乐',
        'http://all.wasu.cn/index/cid/32' => '体育',
      }.each do |category_link, category_name|

        puts "load #{category_link}"

        category = Category.find_or_create_by_name_and_kind category_name, "hot"

        category_page = Nokogiri::HTML(open(category_link))
        category_page.css('#publish dl').reverse.each do |dl|
          begin 
            image = dl.css('dt a img').first.attributes['original'].value
            movie_link = dl.css('dt a').first
            actors = dl.css('dd p')[2].css('a').map{|a|a.content}
            #打开电影页面
            video = Video.find_by_origin_url_and_kind movie_link['href'], "hot"
            if video
              video.update_attributes :category => category, :published => true
            else
              movie_page = open_link(movie_link['href'])
              #info = movie_page.css('.play_filmcont p').last.at('#infoL').content.strip.split("：").last.to_s
              movie_name = movie_page.css('.movie_l h3').first.content
              video = Video.find_or_create_by_name_and_kind movie_name, "hot"
              video.generate_cover(image)
              link = movie_page.at('a.f_download')['onclick'].split("'")[3].strip

              video.update_attributes :link => link, :category => category, :origin_url => movie_link['href'],
                :kind => 'hot', :has_clip => false, :published => true
              actors.each do |actor_name|
                actor = Actor.find_or_create_by_name actor_name
                video.actors << actor
              end
              video.save
              puts "########  load video #{video.name} #{video.link}"
            end
          rescue #Timeout::Error
            puts "broken link when load video "
          end    
        end
      end
    rescue #Timeout::Error
      puts "broken link "
    end
  end
end
